package cn.com.nes.site.controller.patrolPlan;

import cn.com.nes.common.util.ExcelUtils;
import cn.com.nes.common.util.XzqhUtils;
import cn.com.nes.common.web.CommonResult;
import cn.com.nes.site.entity.dto.patrolPlan.QueryPatrolPlanByQueryDto;
import cn.com.nes.site.entity.vo.patrolPlan.*;
import cn.com.nes.site.entity.vo.workOrder.QueryPatrolPlanEquipmentRecordVo;
import cn.com.nes.site.service.patrolPlan.PatrolService;
import cn.com.nes.site.service.workOrder.dto.QueryPatrolPlanEquipmentRecordDto;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 设备巡检相关信息
 *
 * @author nes
 * @date 2018-11-10 21:22
 */
@Api(tags = {"设备巡检相关信息"})
@Controller
@RequestMapping("/v2/patrol")
public class patrolController {

    @Resource
    private PatrolService patrolService;

    /*@Resource
    private CacheManager cacheManager;*/
    /**
     * 创建巡检计划
     *
     * @param createPatrolPlanVo 巡检计划传参类
     * @param
     * @return
     */
    @RequestMapping(value = "/createPatrolPlan", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<?> createPatrolPlan(@RequestBody @Validated CreatePatrolPlanVo createPatrolPlanVo) {
        return patrolService.createPatrolPlan(createPatrolPlanVo);
    }
    /**
     * 修改巡检计划
     *
     * @param updatePatrolPlanVo 巡检计划传参类
     * @param sessoin
     * @return
     */
    @RequestMapping(value = "/updatePatrolPlan", method = RequestMethod.POST)
    public CommonResult<?> updatePatrolPlan(@RequestBody @Validated UpdatePatrolPlanVo updatePatrolPlanVo, HttpSession sessoin) {
        ///执行新增
        Long res = patrolService.updatePatrolPlan(updatePatrolPlanVo);
        //判断新增是否成功
        if (1L != res) {
            //新增成功
            return CommonResult.ok("修改成功");
        } else {
            //新增失败
            return CommonResult.error("修改失败");
        }
    }
    /**
     * 根据设备,计划获取其检查内容
     * @param vo
     * @return
     */
    @RequestMapping(value = "/queryPatrolDataItem", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<?> queryPatrolDataItem(@RequestBody @Validated QueryPatrolDataItemVo vo) {
        return CommonResult.page(patrolService.queryPatrolDataItem(vo));
    }
 /*   *//**
     * 根据计划ID和设备ID删除用户巡检设备记录
     *
     *//*
    @PostMapping(value = "/delPatrolPlanEquipmentRecord")
    public CommonResult<?> delPatrolPlanEquipmentRecord(@RequestBody Map<String,String> map) {
        String patrolPlanId = map.get("patrolPlanId");
        String sbId = map.get("sbId");
        Integer i = patrolService.delPatrolPlanEquipmentRecord(patrolPlanId,sbId);
        if (i>0) {
            Cache cache = cacheManager.getCache("patrolPlanCount");
            cache.clear();
            return CommonResult.ok("删除成功");
        }
        return CommonResult.error("删除失败");
    }*/

    /**
     * 查询巡检计划
     * @param vo
     * @return
     */
    @RequestMapping(value = "/queryPatrolPlanByQuery", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<QueryPatrolPlanByQueryDto> queryPatrolPlanByQuery(@RequestBody @Validated QueryPatrolPlanByQueryVo vo) {
        return CommonResult.page(patrolService.queryPatrolPlanByQuery(vo));
    }

    /**
     * 根据条件获取当前用户巡检设备记录
     *
     */
    @RequestMapping(value = "/queryPatrolPlanEquipmentRecordByQuery", method = RequestMethod.POST)
    @ResponseBody
    public CommonResult<QueryPatrolPlanEquipmentRecordDto> queryPatrolPlanEquipmentRecordByQuery(@RequestBody QueryPatrolPlanEquipmentRecordVo vo,HttpServletResponse response) throws Exception {
        Long userId = vo.getUserInfo().getCallCenterUserId();
        vo.setUserId(userId);
        vo.setCompanyId(Long.parseLong(vo.getOperateUserCallCenterCompanyId()));
        String xzqhdms = vo.getUserInfo().getAreacode();
        String[] strings = XzqhUtils.getXzqhdms(xzqhdms);
        vo.setXzqhdms(strings);
        //根据条件获取当前用户巡检设备记录
        Page<QueryPatrolPlanEquipmentRecordDto> page = patrolService.queryPatrolPlanEquipmentRecordByQuery(vo);

        if(vo.getIsExport() != null && vo.getIsExport() == 1) {
            String title = "巡检数据";
            if(vo.getStatus() != null && vo.getStatus() == 3) {
                title = "待审核巡检";
            } else if(vo.getStatus() != null && vo.getStatus() == 2) {
                title = "巡检失败";
            }
            String[] titleList = new String[]{"序号", "户主姓名", "户主电话", "区域", "详细地址","品牌","出保日期", "状态", "巡检人", "巡检时间", "检查记录", "设备损坏情况"};
            String[] typeList =  new String[]{"String", "String", "String", "String", "String", "String", "String", "String", "String", "date", "String", "String"};
            String[] fieldList = new String[]{"no", "name", "phone", "xzqhmc", "address","abbreviation","warrantyExpiryDate", "statusName", "patrolPersonnel", "patrolTime", "resultDesc", "damageLevelName"};
            ExcelUtils.exportData(fieldList, titleList, typeList, page.getRecords(), title, response,"report",false);
            return null;
        }
        return CommonResult.page(page);
    }

    /**
     * 处理巡检任务
     *
     * @param handlePatrolPlanEquipmentReccordVo 巡检计划传参类
     * @param
     * @return
     */
    @PostMapping(value = "/handlePatrolPlanEquipmentReccord")
    public CommonResult<?> handlePatrolPlanEquipmentReccord(@RequestBody @Validated HandlePatrolPlanEquipmentReccordVo handlePatrolPlanEquipmentReccordVo) {
        //当taskId为空串时，传入记录状态应该为待巡检，即recordStatus必须为1
        String taskId = handlePatrolPlanEquipmentReccordVo.getTaskId();
        int recordStatus = handlePatrolPlanEquipmentReccordVo.getRecordStatus();
        if (!"no".equals(handlePatrolPlanEquipmentReccordVo.getIsBxj())) {
            if (StrUtil.isEmpty(taskId) && recordStatus != 1) {
                return CommonResult.error("状态不完整，添加任务失败");
            }
        } else {
            handlePatrolPlanEquipmentReccordVo.setTaskId(UUID.randomUUID().toString().replaceAll("-", "").substring(0, 30));
        }
        String loginType = "0";/*登录类型 0-pc, 1-小程序维修师傅, 2-小程序巡检*/
        handlePatrolPlanEquipmentReccordVo.setUserId(handlePatrolPlanEquipmentReccordVo.getUserInfo().getCallCenterUserId());
        ///执行新增
        HashMap<String, Object> res = patrolService.handlePatrolPlanEquipmentRecord(handlePatrolPlanEquipmentReccordVo, Integer.parseInt(loginType));
        if (StrUtil.isNotBlank(String.valueOf(res.get("res")))) {
            if ("1".equals(res.get("res"))) {
                return CommonResult.error("任务状态已更新，请返回列表后重试");
            }
        }

        Long recordId = (Long) res.get("recordId");
        //判断新增是否成功
        if (1L != recordId) {
            //新增成功
            return CommonResult.data(res);
        } else {
            //新增失败
            return CommonResult.error("添加失败");
        }

    }
    /**
     * 关闭计划
     *
     * @param vo
     * @param
     * @return
     */
    @PostMapping("/terminatePlan")
    public CommonResult<?> terminatePlan(@RequestBody HashMap<String, Long> vo) {
        //从入参中获取计划id
        Long id = vo.get("id");
        //判断id是否存在
        if (ObjectUtil.isNull(id)) {
            return CommonResult.error("传入id为空");
        }
        Integer res = patrolService.terminatePlan(id);
        if (res == 1) {
            return CommonResult.ok();
        } else {
            return CommonResult.error("关闭失败");
        }
    }
}
